import React, {useEffect, useState} from 'react';
import axios from "axios";
import {Link, useNavigate} from "react-router-dom";
import {Button, Table, Tag} from "antd";


const AuditList = () => {
    const {username}=JSON.parse(localStorage.getItem('token'))
    const [dataSource,setDataSource]=useState([])
    const navigate=useNavigate()

    const auditList=['未审核','审核中','已通过','未通过']

    const columns = [
        {
            title: '新闻标题',
            dataIndex: 'title',
            render:(title,item)=>{
                return <Link to={`/news-manage/preview/${item.id}`}>{title}</Link>
            }
        },
        {
            title: '作者',
            dataIndex: 'author',
            render:(key)=>{
                return <div>{key}</div>
            }
        },
        {
            title: '分类',
            dataIndex: 'category',
            render:(category)=>{
                return category.title
            }
        },
        {
            title:'审核状态',
            dataIndex:'auditState',
            render:(auditState)=>{
                const colorList=['','orange','green','red']
                return <Tag color={colorList[auditState]}>{auditList[auditState]}</Tag>
            }
        },
        {
            title: '操作',
            render:(item)=>{
                return <div>
                    {
                        item.auditState===1 && <Button danger onClick={()=>{handleRevert(item)}}>撤销</Button>
                    }
                    {
                        item.auditState===2 && <Button onClick={()=>{handlePublish(item)}}>发布</Button>
                    }
                    {
                        item.auditState===3 && <Button type={"primary"} onClick={()=>{
                            navigate(`/news-manage/update/${item.id}`)
                        }}>更新</Button>
                    }
                </div>
            }
        }
    ]

    useEffect(()=>{
        axios(`/news?author=${username}&auditState_ne=0&publishState_lte=1&_expand=category`).then(
            res=>{
                setDataSource(res.data)
            }
        )
    },[username])

    const handleRevert=(item)=>{
        setDataSource(dataSource.filter(data=>data.id!==item.id))
        axios.patch(`/news/${item.id}`,{
            auditState:0
        })
    }
    const handlePublish=(item)=>{
        setDataSource(dataSource.filter(data=>data.id!==item.id))
        axios.patch(`/news/${item.id}`,{
            publishState:2,
            publishTime:Date.now()
        })
    }

    return (
        <div>
            <Table dataSource={dataSource} columns={columns} pagination={{pageSize:10}} rowKey={item=>item.id}/>
        </div>
    );
};

export default AuditList;